# 安装: pip install customtkinter
import customtkinter as ctk
import time
import threading
from pynput.keyboard import Controller as KeyboardController
from datetime import datetime


class ModernKeyboardMover:
    def __init__(self):
        self.keyboard = KeyboardController()
        self.is_running = False
        self.thread = None
        self.interval = 10
        self.press_count = 0
        self.lock = threading.Lock()  # 添加锁以确保线程安全

    def set_interval(self, seconds):
        self.interval = seconds
        with self.lock:
            self.press_count = 0

    def press_space(self):
        self.keyboard.press(' ')
        time.sleep(0.1)
        self.keyboard.release(' ')
        with self.lock:
            self.press_count += 1
        return self.press_count  # 返回当前按键次数

    def start_pressing(self):
        self.is_running = True
        while self.is_running:
            count = self.press_space()
            # 发送按键事件通知给GUI线程
            if hasattr(self, 'on_key_press'):
                self.on_key_press(count)
            time.sleep(self.interval)

    def start(self):
        if not self.is_running:
            self.thread = threading.Thread(target=self.start_pressing, daemon=True)
            self.thread.start()

    def stop(self):
        self.is_running = False


class ModernGUI:
    def __init__(self):
        # 设置CustomTkinter主题
        ctk.set_appearance_mode("light")
        ctk.set_default_color_theme("blue")

        self.root = ctk.CTk()
        self.root.title("键盘自动按键器")
        self.root.geometry("500x500")
        self.root.resizable(True, True)

        self.keyboard_mover = ModernKeyboardMover()
        self.interval_entry = None  # 添加对输入框的引用
        self.setup_ui()

        # 注册按键事件回调
        self.keyboard_mover.on_key_press = self.on_key_press

    def setup_ui(self):
        # 主框架
        main_frame = ctk.CTkFrame(self.root)
        main_frame.pack(fill="both", expand=True, padx=20, pady=20)

        # 标题
        title_label = ctk.CTkLabel(main_frame, text="键盘自动按键器",
                                   font=ctk.CTkFont(size=20, weight="bold"))
        title_label.pack(pady=(10, 20))

        # 间隔时间设置
        interval_frame = ctk.CTkFrame(main_frame)
        interval_frame.pack(fill="x", padx=20, pady=10)

        ctk.CTkLabel(interval_frame, text="间隔时间(秒):").pack(anchor="w")

        self.interval_var = ctk.StringVar(value="10")
        self.interval_entry = ctk.CTkEntry(interval_frame, textvariable=self.interval_var)
        self.interval_entry.pack(fill="x", pady=10)

        ctk.CTkLabel(interval_frame, text="最短5秒",
                     text_color="gray").pack(anchor="w")

        # 控制按钮
        self.toggle_btn = ctk.CTkButton(main_frame, text="开始运行",
                                        command=self.toggle_movement,
                                        height=40, font=ctk.CTkFont(size=14))
        self.toggle_btn.pack(fill="x", padx=20, pady=20)

        # 日志区域
        log_frame = ctk.CTkFrame(main_frame)
        log_frame.pack(fill="both", expand=True, padx=20, pady=(0, 20))

        log_title = ctk.CTkLabel(log_frame, text="运行日志",
                                 font=ctk.CTkFont(weight="bold"))
        log_title.pack(anchor="w", padx=10, pady=5)

        # 日志文本框
        self.log_text = ctk.CTkTextbox(log_frame, height=200)
        self.log_text.pack(fill="both", expand=True, padx=10, pady=(0, 10))

        self.add_log("程序启动完成")

    def add_log(self, message):
        timestamp = datetime.now().strftime("%H:%M:%S")
        log_entry = f"[{timestamp}] {message}\n"
        self.log_text.insert("end", log_entry)
        self.log_text.see("end")

    def on_key_press(self, count):
        """按键事件回调函数"""
        # 在主线程中更新UI
        self.root.after(0, lambda: self.add_log(f"第 {count} 次按键"))

    def toggle_movement(self):
        if not self.keyboard_mover.is_running:
            try:
                seconds = float(self.interval_var.get())
                if seconds < 5:
                    self.add_log("错误：时间间隔不能小于5秒")
                    return
                self.keyboard_mover.set_interval(seconds)
                self.keyboard_mover.start()
                self.toggle_btn.configure(text="停止运行",
                                          fg_color="#E53E3E")
                # 禁用输入框
                self.interval_entry.configure(state="disabled")
                self.add_log(f"开始键盘自动按键，间隔 {seconds} 秒")
            except ValueError:
                self.add_log("错误：请输入有效的时间数值")
        else:
            self.keyboard_mover.stop()
            self.toggle_btn.configure(text="开始运行",
                                      fg_color="#3B82F6")
            # 启用输入框
            self.interval_entry.configure(state="normal")
            self.add_log(f"停止键盘自动按键，本次运行共按键 {self.keyboard_mover.press_count} 次")

    def run(self):
        self.root.mainloop()


if __name__ == "__main__":
    app = ModernGUI()
    app.run()
